<%@page import="java.util.Arrays"%>
<%@page import="kau.vo.AttendInfoAnalysis"%>
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@page import="kau.vo.AttendInfo"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@	page import="java.io.*"%>
<%@	page import="jxl.write.*"%>
<%@	page import="jxl.write.Number"%>
<%@	page import="jxl.*"%>
<%@ page import="java.net.URLDecoder"%>
<%@ page import="java.net.URLEncoder"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<%


File folder=new File("C:\\nems");
if(!folder.exists())  //폴더가 없으면 생성
folder.mkdirs();
File file = new File("C:\\nems","output.xls");


/*BufferedWriter bfWriter = new BufferedWriter(new FileWriter("C:\\xx\\xx.xls"));  
StringBuffer sbData = new StringBuffer();

sbData.append(1 + "\t")
.append(2+ "\t")
.append(3 + "\r\n");

//실제로 적어주는 부분
bfWriter.write(sbData.toString());
bfWriter.flush();*/


WritableWorkbook workbook = Workbook.createWorkbook(new File("C:\\nems","output.xls")); 



ArrayList<AttendInfo>[] periodicalAttendList =null;

String periodical = (String)request.getAttribute("periodical");
String attendAnalysis = request.getParameter("attendAnalysis");

if(attendAnalysis != null){
	ArrayList<AttendInfoAnalysis> attendInfoAnalysisList = (ArrayList) session.getAttribute("attendInfoAnalysisList");
	session.removeAttribute("attendInfoAnalysisList");
	String courseName_ = (String)session.getAttribute("courseName");
	WritableSheet sheet = workbook.createSheet(courseName_+"출석분석", 0);

	
	sheet.addCell(new Label(0,0,"아이디"));
	
	sheet.addCell(new Label(1,0,"이름"));
	sheet.addCell(new Label(2,0,"결석수"));
	sheet.addCell(new Label(3,0,"조퇴수"));
	sheet.addCell(new Label(4,0,"지각수"));
	sheet.addCell(new Label(5,0,"정상출석수"));
	sheet.addCell(new Label(6,0,"출석점수"));
	sheet.addCell(new Label(7,0,"최종점수"));
	sheet.addCell(new Label(8,0,"총수업일수"));
	sheet.addCell(new Label(9,0,"출석일수"));
	sheet.addCell(new Label(10,0,"남은일수"));
	sheet.addCell(new Label(11,0,"진행률"));
	
	for(int i=0; i<attendInfoAnalysisList.size(); i++){
		
		
		Label custId= new Label(0,i+1,attendInfoAnalysisList.get(i).getCustId());
		sheet.addCell(custId);
		Label custName = new Label(1,i+1,attendInfoAnalysisList.get(i).getCustName());
		sheet.addCell(custName);
		Number absenceCnt = new Number(2,i+1,attendInfoAnalysisList.get(i).getAbsenceCnt());
		sheet.addCell(absenceCnt);
		Number earlyLeavingCnt = new Number(3,i+1,attendInfoAnalysisList.get(i).getEarlyLeavingCnt());
		sheet.addCell(earlyLeavingCnt);
		Number lateCnt = new Number(4,i+1,attendInfoAnalysisList.get(i).getLateCnt());
		sheet.addCell(lateCnt);
		Number nomalCnt = new Number(5,i+1,attendInfoAnalysisList.get(i).getNomalCnt());
		sheet.addCell(nomalCnt);
		Number attendGrade = new Number(6,i+1,attendInfoAnalysisList.get(i).getAttendGrade());
		sheet.addCell(attendGrade);
		Number totalGrade = new Number(7,i+1,attendInfoAnalysisList.get(i).getTotalGrade());
		sheet.addCell(totalGrade);
		Number allAttendCnt = new Number(8,i+1,attendInfoAnalysisList.get(i).getAllAttendCnt());
		sheet.addCell(allAttendCnt);
		Number pastAttendCnt = new Number(9,i+1,attendInfoAnalysisList.get(i).getPastAttendCnt());
		sheet.addCell(pastAttendCnt);
		Number leftAttendCnt = new Number(10,i+1,attendInfoAnalysisList.get(i).getLeftAttendCnt());
		sheet.addCell(leftAttendCnt);
		Number progress = new Number(11,i+1,attendInfoAnalysisList.get(i).getProgress());
		sheet.addCell(progress);
	}

	workbook.write(); 
	workbook.close(); 

	////////////////////////////////////////////////////////////////////////////////////////////////

	response.reset();
	response.setContentType("application/octer-stream");
	// 일반파라미터 application/x-www-form-urlencoded 디폴트로 설정 되있다!
	// 파일은 다르기 때문에 response 값을 바꾼것임

	// 해더의 이름에 내가 원하는 전송할 파일 이름을 넣은 것임
	// 파일이름은 브라우저 설정 문자셋으로 바뀐것으로 넣는다! 
	response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(courseName_+"_출석분석"+".xls", "utf-8") + ";");
}
else if(periodical == null && attendAnalysis ==null){
	ArrayList<AttendInfo> attendInfoList = (ArrayList)request.getAttribute("attendInfoList");
	String custId_= attendInfoList.get(0).getCustId();
	String custName_= attendInfoList.get(0).getCustName();
	String courseName_ = attendInfoList.get(0).getCourseName();
	WritableSheet sheet = workbook.createSheet(courseName_+"_"+custId_, 0);

	Label custId = new Label(0,0,"아이디");
	sheet.addCell(custId);
	Label custName = new Label(1,0,"이름");
	sheet.addCell(custName);
	Label courseName = new Label(2,0,"코스명");
	sheet.addCell(courseName);
	Label day = new Label(3,0,"날짜");
	sheet.addCell(day);
	Label checkInTime = new Label(4,0,"체크인시간");
	sheet.addCell(checkInTime);
	Label checkOutTime = new Label(5,0,"체크아웃시간");
	sheet.addCell(checkOutTime);
	Label state = new Label(6,0,"출결정보");
	sheet.addCell(state);
	for(int i=0;i<attendInfoList.size();i++){
		custId= new Label(0,i+1,attendInfoList.get(i).getCustId());
		sheet.addCell(custId);
		custName = new Label(1,i+1,attendInfoList.get(i).getCustName());
		sheet.addCell(custName);
		courseName = new Label(2,i+1,attendInfoList.get(i).getCourseName());
		sheet.addCell(courseName);
		day = new Label(3,i+1,attendInfoList.get(i).getDay());
		sheet.addCell(day);
		checkInTime = new Label(4,i+1,attendInfoList.get(i).getCheckInTime());
		sheet.addCell(checkInTime);
		checkOutTime = new Label(5,i+1,attendInfoList.get(i).getCheckOutTime());
		sheet.addCell(checkOutTime);
		state = new Label(6,i+1,attendInfoList.get(i).getState());
		sheet.addCell(state);
	}

	workbook.write(); 
	workbook.close(); 

	////////////////////////////////////////////////////////////////////////////////////////////////

	response.reset();
	response.setContentType("application/octer-stream");
	// 일반파라미터 application/x-www-form-urlencoded 디폴트로 설정 되있다!
	// 파일은 다르기 때문에 response 값을 바꾼것임

	// 해더의 이름에 내가 원하는 전송할 파일 이름을 넣은 것임
	// 파일이름은 브라우저 설정 문자셋으로 바뀐것으로 넣는다! 
	response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(courseName_+"_"+custName_+".xls", "utf-8") + ";");
}



//기간별
else if(periodical!=null){

	String startDate_ = (String)request.getAttribute("startDate");
	String endDate_ = (String)request.getAttribute("endDate");
	ArrayList<AttendInfo> attendInfoList = (ArrayList)request.getAttribute("attendInfoList");
	List dayList = (List) request.getAttribute("dayList");
	WritableSheet[] sheetList = new WritableSheet[dayList.size()];
	Label custId,custName,courseName,day,checkInTime,checkOutTime,state;
	periodicalAttendList = new ArrayList[dayList.size()];
	for(int i=0; i<dayList.size();i++)
	{
		sheetList[i]= workbook.createSheet(dayList.get(i).toString(), i);
		custId = new Label(0,0,"아이디");
		sheetList[i].addCell(custId);
		custName = new Label(1,0,"이름");
		sheetList[i].addCell(custName);
		courseName = new Label(2,0,"코스명");
		sheetList[i].addCell(courseName);
		day = new Label(3,0,"날짜");
		sheetList[i].addCell(day);
		checkInTime = new Label(4,0,"체크인시간");
		sheetList[i].addCell(checkInTime);
		checkOutTime = new Label(5,0,"체크아웃시간");
		sheetList[i].addCell(checkOutTime);
		state = new Label(6,0,"출결정보");
		sheetList[i].addCell(state);
		
		periodicalAttendList[i] = new ArrayList<AttendInfo>();
		for(int j=0;j<attendInfoList.size();j++){
			
			if(dayList.get(i).toString().equals(attendInfoList.get(j).getDay().toString())){
				periodicalAttendList[i].add(attendInfoList.get(j));
			}
		}
	}
	
	//custId= new Label(0,1,periodicalAttendList.length);
	
	//sheetList[0].addCell(custId);
	
	// periodicalAttendList[] : 요일별로 AttendInfo가 저장되있는배열
	for(int i=0;i<periodicalAttendList.length;i++)	// length =3
	{
		for(int j=0;j<periodicalAttendList[i].size();j++){
			
			custId= new Label(0,j+1,periodicalAttendList[i].get(j).getCustId());
			sheetList[i].addCell(custId);
			custName = new Label(1,j+1,periodicalAttendList[i].get(j).getCustName());
			sheetList[i].addCell(custName);
			courseName = new Label(2,j+1,periodicalAttendList[i].get(j).getCourseName());
			sheetList[i].addCell(courseName);
			day = new Label(3,j+1,periodicalAttendList[i].get(j).getDay());
			sheetList[i].addCell(day);
			checkInTime = new Label(4,j+1,periodicalAttendList[i].get(j).getCheckInTime());
			sheetList[i].addCell(checkInTime);
			checkOutTime = new Label(5,j+1,periodicalAttendList[i].get(j).getCheckOutTime());
			sheetList[i].addCell(checkOutTime);
			state = new Label(6,j+1,periodicalAttendList[i].get(j).getState());
			sheetList[i].addCell(state);
			
		}
	}
	String courseName_ = attendInfoList.get(0).getCourseName();


	
	

	workbook.write(); 
	workbook.close(); 

	////////////////////////////////////////////////////////////////////////////////////////////////

	response.reset();
	response.setContentType("application/octer-stream");
	// 일반파라미터 application/x-www-form-urlencoded 디폴트로 설정 되있다!
	// 파일은 다르기 때문에 response 값을 바꾼것임

	// 해더의 이름에 내가 원하는 전송할 파일 이름을 넣은 것임
	// 파일이름은 브라우저 설정 문자셋으로 바뀐것으로 넣는다! 
	response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(courseName_+"_"+startDate_+"_"+endDate_+".xls", "utf-8") + ";");
	
}
response.setHeader("Content-Transper-Encoding", "binary");
// 사이즈도 알려줘야 한다

response.setContentLength((int)file.length());
// cache에 안 넣을 거다! 
response.setHeader("Pargma", "no-cache");
// Expires 는 또 무슨 뜻인가염 넹?!
response.setHeader("Expires", "-1");

byte[] data = new byte[1024 * 1024];
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file));
// response가 사용하는 OutputStream()을 out 스트림으로 사용 
BufferedOutputStream fos = new BufferedOutputStream(response.getOutputStream());

int count = 0;
while((count = fis.read(data)) != -1){
 fos.write(data);
}

if(fis != null) fis.close();
if(fos != null) fos.close();

out.clear();
out = pageContext.pushBody();


%>
<%=periodicalAttendList %>
</body>
</html>